﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.rtgs.stp_rule_trn" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using RTGS.Library;
using RTGS.Library.DataAccess.Rtgs;
using RTGS.Library.Entities.Rtgs;
using RTGS.Library.Enum;
using RTGS.Web.support;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;

namespace RTGS.Web.ajaxhandler.rtgs
{

public class stp_rule_trn : BaseHandler
    {
        private    stpRuleTrnRepo stpRuleTrnDal = new stpRuleTrnRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private string MethodName = string.Empty;

        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            stpRuleTrn obj = new stpRuleTrn();

            if (context.Request.Params["trncode"] != null)
                obj.ruleTrntrncode = context.Request.Params["trncode"];
            if (context.Request.Params["rulecode"] != null)
                obj.ruleTrnrulecode = context.Request.Params["rulecode"];


            if (stpRuleTrnDal.Save(obj))
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Insert stpRuleTrn Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRuleTrnDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Insert stpRuleTrn Error";
                log.logMessage = stpRuleTrnDal.GetErrorMessage();

            }

            log.logSource = "spt_priority.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            stpRuleTrn obj = new stpRuleTrn();

            if (context.Request.Params["trncode"] != null)
                obj.ruleTrntrncode = context.Request.Params["trncode"];
            if (context.Request.Params["rulecode"] != null)
                obj.ruleTrnrulecode = context.Request.Params["rulecode"];
            if (context.Request.Params["id"] != null)
                obj.ruleTrnid = Convert.ToInt32(context.Request.Params["id"]);

            

            if (stpRuleTrnDal.Update(obj))
            {
                helper.Data = obj;
                helper.Message = "Data has been updated!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Update stpRuleTrn Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRuleTrnDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Update stpRuleTrn Error";
                log.logMessage = stpRuleTrnDal.GetErrorMessage();
            }

            log.logSource = "stp_Rule_Trn.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string Delete(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            bool isSuccess = true;
            string[] ids = context.Request.Params["id"].Split(',');
            foreach (string id in ids)
            {
                isSuccess = stpRuleTrnDal.Delete(Convert.ToInt32(id));
                if (!isSuccess) break;
            }

            if (isSuccess)
            {
                helper.IsSuccess = true;
                helper.Message = "Data has been deleted!";

                log = new sysTLog();
                log.logEvent = "Delete stpRuleTrn Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRuleTrnDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Delete stpRuleTrn Error";
                log.logMessage = stpRuleTrnDal.GetErrorMessage();
            }

            log.logSource = "stp_Rule_Trn.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? stpRuleTrn.Fields.ruleTrntrncode : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            string field = ((context.Request.Params["field"]) == null ? string.Empty : context.Request.QueryString["field"].ToString());
            string operand = ((context.Request.Params["operand"]) == null ? string.Empty : context.Request.QueryString["operand"].ToString());
            string value = ((context.Request.Params["value"]) == null ? string.Empty : context.Request.QueryString["value"].ToString());

            string parameters = string.Empty;

            if (!string.IsNullOrEmpty(value))
            {
                field = operand.ToLower().Contains("like") ? "LOWER(" + field + ")" : field;
                field = field.ToLower().Contains("date") ? "CONVERT(char(8), " + field + ", 112)" : field;

                var filter = operand.ToLower().Contains("like") ? "'%" + value.ToLower() + "%'" :
                    field.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(value) + "'" : "'" + value + "'"; // TextBox Filter

                parameters = " WHERE " + field + " " + operand + " " + filter;
            }

            int totalCount = Convert.ToInt32(stpRuleTrnDal.SelectScalar(SQL.Function.Aggregate.Count, stpRuleTrn.Fields.ruleTrntrncode, parameters));

            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);

            List<stpRuleTrn> pagedList = stpRuleTrnDal.GetList(pageSize, page, sidx, sord, parameters);

            if (!string.IsNullOrEmpty(stpRuleTrnDal.GetErrorMessage()))
            {
                log = new sysTLog();
                log.logEvent = "GetData stpRuleTrn error ";
                log.logMessage = stpRuleTrnDal.GetErrorMessage();

            }
            else
            {
                log = new sysTLog();
                log.logEvent = "View Data stpRuleTrn Success ";
                log.logMessage = stpRuleTrnDal.GetErrorMessage();
            }

            log.logSource = "stp_Rule_Trn.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

       

        #endregion

    }
}